<?php

namespace app\cps\service;

use app\model\Videos;
use app\model\VideoDetails;
use app\model\SetFollowDrama;
use think\facade\Cache;
use think\facade\Db;
use app\model\VideoPayConfig;
use app\common\Error;
use app\model\OfficialAccounts;
use app\model\ResponsibilityPerson;
use app\model\WatchPayRecord;
use app\model\Link;

class VideoService
{
    private $videosModel;
    private $detailModel;
    private $setFollowDramaModel;
    private $videoPayConfigModel;
    private $officialAccountsModel;
    private $responsibilityPersonModel;
    private $watchPayRecordModel;
    private $linkModel;

    public function __construct(Videos $videosModel, VideoDetails $detailModel, SetFollowDrama $setFollowDramaModel, VideoPayConfig $videoPayConfigModel, OfficialAccounts $officialAccountsModel, ResponsibilityPerson $responsibilityPersonModel, WatchPayRecord $watchPayRecordModel, Link $linkModel)
    {
        $this->videosModel = $videosModel;
        $this->detailModel = $detailModel;
        $this->setFollowDramaModel = $setFollowDramaModel;
        $this->videoPayConfigModel = $videoPayConfigModel;
        $this->officialAccountsModel = $officialAccountsModel;
        $this->responsibilityPersonModel = $responsibilityPersonModel;
        $this->watchPayRecordModel = $watchPayRecordModel;
        $this->linkModel = $linkModel;
    }

    // 获取短剧列表
    public function getShortPlayList($params, $userInfo)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 15;

        $where = [
            ['is_delete', '=', 0]
        ];
        if (!empty($params['id'])) $where[] = ['id', '=', $params['id']];
        if (!empty($params['name'])) $where[] = ['name', 'like', '%'.$params['name'].'%'];

        $cpsId = $userInfo['cps_user_id'];
        $pData = $this->responsibilityPersonModel->getInfoById($cpsId, 'pid, is_distributor, video_ids, is_branch_office_manage');

        if (!empty($pData['pid'])) {
            $pData = $this->responsibilityPersonModel->getInfoById($pData['pid'], 'is_distributor, video_ids');
            if (!empty($pData['is_distributor'])) {
                $videoIds = explode(',', $pData['video_ids']);
                $where[] = ['id', 'in', $videoIds];
            }
        } else if (!empty($pData['is_distributor'])) {
            if (!empty($pData['pid'])) {
                $pData = $this->responsibilityPersonModel->getInfoById($pData['pid'], 'video_ids');
            }
            $videoIds = explode(',', $pData['video_ids']);
            $where[] = ['id', 'in', $videoIds];
        }

        $fields = 'id, cover_img, name, is_free, sylloge, status, is_shelves, total_consume, frequency, number, update_sort, synopsis,launch_start_time,is_copy,original_id';
        $data = $this->videosModel->getPagingDataByWhere($where, $page, $limit, $fields, 'created_at desc');

        if ($data['data']) {
            $redis = Cache::store('redis')->handler();
            $redis->select(2);
            $videoKey = config('redis_key.video_statistic_count_key');
            $videoInfo = $redis->hGetAll($videoKey) ?: [];

            $videoIds = array_column($data['data'], 'id');

            // 自定义收费配置
            // $customChargeConfigureData = $this->videoPayConfigModel->getDataByWhere(['video_id' => $videoIds, 'status' => 0], 'video_id, sort, pay_amount');
            // $customChargeConfigure = array_column($customChargeConfigureData, NULL, 'video_id');

            // 总后台公共配置
            $detailData = $this->detailModel->getDataByWhere(['video_id' => $videoIds, 'is_pay' => 1], 'video_id, sort, pay_amount', 'sort asc');

            $ids = $detailResult = [];
            foreach ($detailData as $key => $item) {
                if (!in_array($item['video_id'], $ids)) {
                    $detailResult[$item['video_id']] = $item;
                }
                $ids[] = $item['video_id'];
            }

            foreach ($data['data'] as $key => $item) {
                // if (!empty($customChargeConfigure[$item['id']])) {
                //     // 自定义
                //     $data['data'][$key]['sort'] = $customChargeConfigure[$item['id']]['sort'];
                //     $data['data'][$key]['pay_amount'] = $customChargeConfigure[$item['id']]['pay_amount'];
                // } else 
                if (!empty($detailResult[$item['id']])) {
                    // 公共
                    $data['data'][$key]['sort'] = $detailResult[$item['id']]['sort'];
                    $data['data'][$key]['pay_amount'] = intval($detailResult[$item['id']]['pay_amount']);
                } else {
                    $data['data'][$key]['sort'] = '无';
                    $data['data'][$key]['pay_amount'] = '无需付费';
                }

                $total_consume_cache = $videoInfo['total_consume_'.$item['id']] ?? 0;
                $data['data'][$key]['total_consume'] = $item['total_consume'] + $total_consume_cache;

                $frequency_cache = $videoInfo['frequency_'.$item['id']] ?? 0;
                $data['data'][$key]['frequency'] = $item['frequency'] + $frequency_cache;

                $number_cache = $videoInfo['number_'.$item['id']] ?? 0;
                $data['data'][$key]['number'] = $item['number'] + $number_cache;
            }
        }

        return $data;
    }

    // 获取指定短剧的剧集列表
    public function getDramaList($videoId, $userInfo)
    {
        $cpsId = $userInfo['cps_user_id'];
        $info = $this->responsibilityPersonModel->getInfoById($cpsId, 'is_distributor, pid');
        $data = $this->detailModel->getAllDataByVideoId($videoId, 'id, video_id, sort, third_url as url, is_pay');
        $count = count($data);
        if (!empty($info['is_distributor']) || !empty($info['pid'])) {
            // 分销可下载70%
            $count = ceil($count*0.7);
        }

        $setFollowDrama = [];

        if (!empty($userInfo['is_branch_office_manage']) && $userInfo['is_branch_office_manage'] == 1) {
            //
        } else {
            $usedOfficialAccountId = $userInfo['cps_used_official_account_id'];
            $setFollowDramaData = $this->setFollowDramaModel->getInfoByWhere(['official_account_id' => $usedOfficialAccountId, 'video_id' => $videoId], 'video_detail_id');

            foreach ($setFollowDramaData as $item) {
                $setFollowDrama[$item] = $item;
            }
        }

        // 自定义收费配置
        $customChargeConfigureData = $this->videoPayConfigModel->getInfoByWhere(['video_id' => $videoId, 'status' => 0], 'sort');

        foreach ($data as $key => $item) {
            $data[$key]['is_set_follow_drama'] = empty($setFollowDrama[$item['id']]) ? 0 : 1;

            if ($customChargeConfigureData) {
                if ($item['sort'] >= $customChargeConfigureData['sort']) {
                    $data[$key]['is_pay'] = 1;
                } else {
                    $data[$key]['is_pay'] = 0;
                }
            }
            $data[$key]['is_download'] = $key < $count ? 1 : 0;
        }

        // $videosData = $this->videosModel->getInfoById($videoId, 'launch_start_time, created_at');
        // if (empty($videosData['launch_start_time'])) {
        //     $videosData['launch_start_time'] = $videosData['created_at'];
        // }
        return $data;
    }

    // 设置/取消关注剧集
    public function setFollowDrama($videoDetailId, $userInfo)
    {
        if (!empty($userInfo['is_branch_office_manage']) && $userInfo['is_branch_office_manage'] == 1) {
            // 分公司负责人不能设置
            return ['message' => Error::NOT_OPERATE_AUTH_MESSAGE];
        }
        $data = $this->detailModel->getInfoById($videoDetailId, 'id, sort, video_id');

        $usedOfficialAccountId = $userInfo['cps_used_official_account_id'];

        $saveData = $where = [
            'official_account_id' => $usedOfficialAccountId,
            'video_id' => $data['video_id'],
            'video_detail_id' => $videoDetailId
        ];

        $setFollowDramaData = $this->setFollowDramaModel->getInfoByWhere($where, 'id');

        if ($setFollowDramaData) {
            // 取消关注剧集
            $bool = $this->setFollowDramaModel->destroy($setFollowDramaData['id']);
        } else {
            // 判断是否设置了这个短剧的其他剧集为关注剧集
            $where = [
                'official_account_id' => $usedOfficialAccountId,
                'video_id' => $data['video_id']
            ];
            $isSetFollowDramaData = $this->setFollowDramaModel->getInfoByWhere($where, 'id');

            if ($isSetFollowDramaData) {
                $this->setFollowDramaModel->destroy($isSetFollowDramaData['id']);
            }
            // 设置关注章节
            $saveData['follow_sort'] = $data['sort'];
            $saveData['created_at'] = time();
            $bool = $this->setFollowDramaModel->edit($saveData);
        }

        if (!$bool) {
            return ['message' => Error::FAIL_MESSAGE];
        }

        return [];
    }

    // 获取短剧下拉列表
    public function getShortPlaySelectList($params, $userInfo = null)
    {
        $where = [
            ['is_delete', '=', 0]
        ];

        if (isset($params['is_shelves']) && empty($params['is_shelves'])) {
            // $where[] = ['is_shelves', '=', 0];
        } else {
            $where[] = ['is_shelves', '=', 1];
        }

        // 获取登陆用户信息
        $userId = $userInfo['cps_user_id'];
        $personArr = $this->responsibilityPersonModel->getInfoById($userId, 'pid, video_ids, is_distributor');

        $distributorInfo = [];
        if (!empty($personArr['pid'])) {
            $distributorInfo = $this->responsibilityPersonModel->getInfoById($personArr['pid'], 'is_distributor, video_ids');
        }

        //  如果存在父级，且父级是分销商，需要继承父级分销商的video_ids
        if (!empty($personArr['is_distributor'])) {
            if (!empty($personArr['video_ids'])) {
                $videoIds = explode(',', $personArr['video_ids']);
                $where[] = ['id', 'in', $videoIds];
            }
        } elseif (!empty($distributorInfo['is_distributor'])) {
            if (!empty($distributorInfo['video_ids'])) {
                $videoIds = explode(',', $distributorInfo['video_ids']);
                $where[] = ['id', 'in', $videoIds];
            }
        }

        $data = $this->videosModel->getDataByWhere($where, 'id, name, sylloge');
        if(!empty($data)) {
            foreach($data as $key => $value) {
                $data[$key]['name'] = $value['id'].'-'.$value['name'];
            }
        }
        return $data;
    }

    /**
     * 自定义短剧收费配置列表
     */
    public function getCustomChargeConfigureList($params, $userInfo)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;
        $where = [];

        $usedOfficialAccountId = $userInfo['cps_used_official_account_id'];

        $responsibilityPersonId = $userInfo['cps_user_id'];
        $distributorInfo = $this->responsibilityPersonModel->getInfoById($responsibilityPersonId, 'is_distributor');

        if (!empty($userInfo['is_branch_office_manage']) && $userInfo['is_branch_office_manage'] == 1) {
            // 分公司
            $cpsUserId = $userInfo['cps_user_id'];
            $responsibilityPersonData = $this->responsibilityPersonModel->getDataByWhere(['pid' => $cpsUserId], 'id');
            $responsibilityPersonIds = array_column($responsibilityPersonData, 'id');
            $responsibilityPersonIds[] = $cpsUserId;

            $where[] = ['responsibility_person_id', 'in', $responsibilityPersonIds];
        } else if (!empty($distributorInfo['is_distributor'])) {
            // 分销商能查看他下面的投手的数据
            $responsibilityPersonData = $this->responsibilityPersonModel->getDataByWhere(['pid' => $responsibilityPersonId], 'id');
            $responsibilityPersonIds = array_column($responsibilityPersonData, 'id');
            $where[] = ['official_account_id', '=', $usedOfficialAccountId];
            $where[] = ['responsibility_person_id', 'in', $responsibilityPersonIds];
        } else if ($userInfo['cps_user_name'] != config('enum.cps_user_name')) {
            $where[] = ['responsibility_person_id', '=', $userInfo['cps_user_id']];
            $where[] = ['official_account_id', '=', $usedOfficialAccountId];
        } else {
            $where[] = ['official_account_id', '=', $usedOfficialAccountId];
        }

        // 名称搜索
        if (!empty($params['name'])) {
            $where[] = ['name', 'like', '%'.$params['name'].'%'];
        }

        // 名称搜索
        if (!empty($params['video_id'])) {
            $where[] = ['video_id', '=', $params['video_id']];
        }

        $data = $this->videoPayConfigModel->getPagingDataByWhere($where, $page, $limit, 'id, video_id, sort, pay_amount, status, created_at, updated_at, responsibility_person_id, name');

        if ($data['data']) {
            $videoIds = array_column($data['data'], 'video_id');

            $video = $this->videosModel->getDataByIds($videoIds, 'id, name');
            $videoData = array_column($video, 'name', 'id');

            $responsibilityPersonIds = array_column($data['data'], 'responsibility_person_id');
            $responsibilityPerson = $this->responsibilityPersonModel->getDataByWhere(['id' => $responsibilityPersonIds], 'id, name');
            $responsibilityPersonData = array_column($responsibilityPerson, 'name', 'id');

            foreach ($data['data'] as $key => $value) {
                $data['data'][$key]['video_name'] = empty($videoData[$value['video_id']]) ? '' : $videoData[$value['video_id']];
                $data['data'][$key]['responsibility_person'] = empty($responsibilityPersonData[$value['responsibility_person_id']]) ? '' : $responsibilityPersonData[$value['responsibility_person_id']];
            }
        }

        return $data;
    }

    // 自定义短剧收费配置详情
    public function getCustomChargeConfigureDetail($id)
    {
        $data = $this->videoPayConfigModel->getInfoById($id, 'id, video_id, sort, pay_amount, status, name');
        return $data;
    }

    // 添加/编辑自定义短剧收费配置
    public function editCustomChargeConfigure($params, $userInfo)
    {
        $responsibilityPersonId = $userInfo['cps_user_id'];
        $usedOfficialAccountId = $userInfo['cps_used_official_account_id'];

        if (empty($params['id'])) {
            $params['created_at'] = time();
            $officialAccountId = $userInfo['cps_used_official_account_id'];
            $params['official_account_id'] = $officialAccountId;
            $params['responsibility_person_id'] = $responsibilityPersonId;
            // $data = $this->videoPayConfigModel->getInfoByWhere(['official_account_id' => $usedOfficialAccountId, 'responsibility_person_id' => $responsibilityPersonId, 'video_id' => $params['video_id']], 'id');
            // if ($data) {
            //     return ['message' => Error::CUSTOM_CONFIGURATION_ALREADY_EXISTS];
            // }
        } else {
            $params['updated_at'] = time();
        }

        $id = $this->videoPayConfigModel->edit($params);
        return $id ? true : false;
    }

    // 短剧收费设置下拉列表
    public function paySettingSelect($params, $userInfo)
    {
        $where = [
            'video_id' => $params['video_id'], 
            'status' => 0,
            'name' => Db::raw('IS NOT NULL')
        ];

        if (!empty($userInfo['is_branch_office_manage']) && $userInfo['is_branch_office_manage'] == 1) {
            $cpsUserId = $userInfo['cps_user_id'];
            $responsibilityPersonData = $this->responsibilityPersonModel->getDataByWhere(['pid' => $cpsUserId], 'id');
            $responsibilityPersonIds = array_column($responsibilityPersonData, 'id');
            $responsibilityPersonIds[] = $cpsUserId;
            $where['responsibility_person_id'] = $responsibilityPersonIds;
        } else if (!empty($distributorInfo['is_distributor'])) {
            $where['official_account_id'] = $userInfo['cps_used_official_account_id'];
            // 分销商能查看他下面的投手的数据
            $responsibilityPersonData = $this->responsibilityPersonModel->getDataByWhere(['pid' => $responsibilityPersonId], 'id');
            $responsibilityPersonIds = array_column($responsibilityPersonData, 'id');
            $where['responsibility_person_id'] = $responsibilityPersonIds;
        } else if ($userInfo['cps_user_name'] != config('enum.cps_user_name')) {
            $where['official_account_id'] = $userInfo['cps_used_official_account_id'];
            $where['responsibility_person_id'] = $userInfo['cps_user_id'];
        } else {
            $where['official_account_id'] = $userInfo['cps_used_official_account_id'];
        }

        $data = $this->videoPayConfigModel->getDataByWhere($where, 'id, name');
        // foreach ($data as $key => $value) {
        //     if (empty($value['name'])) {
        //         $responsibilityPerson = $this->responsibilityPersonModel->getInfoById(['id' => $value['responsibility_person_id']], 'name');
        //         $data[$key]['name'] = $responsibilityPerson['name'].'的收费设置';
        //     }
        // }

        return $data;
    }

    // 删除自定义短剧收费配置
    public function deleteCustomChargeConfigure($id)
    {
        $bool = $this->videoPayConfigModel->edit(['id' => $id, 'status' => 1]);
        return $bool ? true : false;
    }

    // 智能推送设置
    public function pushSetting($params, $userInfo)
    {
        $officialAccountId = $userInfo['cps_used_official_account_id'];

        $id = $this->officialAccountsModel->edit([
            'id' => $officialAccountId,
            'watch_reminder' => $params['watch_reminder'],
            'sign_reminder' => $params['sign_reminder'],
            'updated_at' => time(),
            'responsibility_person_id' => $userInfo['cps_user_id']
        ]);

        return $id ? true : false;
    }

    // 获取智能推送设置
    public function getPushSetting($userInfo)
    {
        $officialAccountId = $userInfo['cps_used_official_account_id'];

        $data = $this->officialAccountsModel->getInfoById($officialAccountId, 'watch_reminder, sign_reminder');

        return $data;
    }

    // 短剧详情数据
    public function getDetailCharge($params)
    {
        $videoId = $params['id'];
        $videoName = $params['name'];
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 15;

        $data = $this->detailModel->getPagingDataByWhere(['video_id' => $videoId], $page, $limit, 'id, name, is_pay, pay_amount, number, today_number');

        if ($data['data']) {
            $redis = Cache::store('redis')->handler();
            $redis->select(2);
            $videoDetailKey = config('redis_key.video_detail_statistic_count_key').$videoId;
            $detailInfo = $redis->hGetAll($videoDetailKey) ?: [];

            $ids = array_column($data['data'], 'id');

            $consumeDate = $this->watchPayRecordModel->getInfo(['video_id' => $videoId, 'video_detail_id' => $ids], 'video_detail_id, money, consume_date');
            $consume = [];
            foreach ($consumeDate as $key => $value) {
                $consume[$value['video_detail_id']][] = $value;
            }

            $toDay = date('Ymd');
            foreach ($data['data'] as $key => $value) {
                $totalConsume = $toDayConsume = 0;
                $watchUserNum = $toDayWatchUserNum = 0;
                if (!empty($consume[$value['id']])) {
                    foreach ($consume[$value['id']] as $k => $item) {
                        $totalConsume += $item['money'];
                        $watchUserNum += 1;
                        if ($item['consume_date'] == $toDay) {
                            $toDayConsume += $item['money'];
                            $toDayWatchUserNum += 1;
                        }
                    }
                }
                $today_number = $value['today_number'] + ($detailInfo['today_number_'.$value['id']] ?? 0);
                $number = $value['number'] + ($detailInfo['number_'.$value['id']] ?? 0);
                $data['data'][$key]['video_name'] = $videoName;
                $data['data'][$key]['total_consume'] = $totalConsume;
                $data['data'][$key]['today_consume'] = $toDayConsume;
                $data['data'][$key]['watch_user_num'] = empty($watchUserNum) ? (int)$number : $watchUserNum;
                $data['data'][$key]['today_watch_user_num'] = empty($today_number) ? $toDayWatchUserNum : (int)$today_number;
            }
        }
        return $data;
    }

    // 批量设置短剧自定义收费
    public function batchSettingVideoPay($params)
    {
        $linkIds = explode(',', $params['link_ids']);
        $linkData = $this->linkModel->getDataByWhere(['id' => $linkIds], 'video_id');

        $videoIds = array_column($linkData, 'video_id');
        $videoId = array_unique($videoIds);

        // 只能修改一部短剧的链接
        if (count($videoId) > 1) {
            return ['message' => Error::PLEASE_SELECT_THE_LINK_FOR_THE_SPECIFIED_SHORT_PLAY];
        }

        $videoPayConfigModelData = $this->videoPayConfigModel->getInfoById($params['video_pay_setting_id'], 'video_id');

        // 自定义的短剧收费对应的短剧与所选链接所属的短剧需对应
        if ($videoPayConfigModelData['video_id'] != $videoId[0]) {
            return ['message' => Error::THE_SELECTED_CUSTOM_SHORT_DRAMA_FEE_NOT_THE_SELECTED_LINK];
        }

        $data = [];
        foreach ($linkIds as $id) {
            $data[] = [
                'id' => $id,
                'video_pay_setting_id' => $params['video_pay_setting_id'],
                'updated_at' => time()
            ];
        }

        // 批量修改
        $num = $this->linkModel->saveAll($data);
        if (!$num) {
            return ['message' => Error::SETTING_FAIL];
        }

        return [];
    }
}